<?
//Get a GET vairable, if the variable is not present, take the default value
function elapsed_time($timestamp, $precision = 2) { 
  $time = time() - $timestamp; 
  $a = array('decade' => 315576000, 'year' => 31557600, 'month' => 2629800, 'week' => 604800, 'day' => 86400, 'hour' => 3600, 'min' => 60, 'sec' => 1); 
  $i = 0; 
    foreach($a as $k => $v) { 
      $$k = floor($time/$v); 
      if ($$k) $i++; 
      $time = $i >= $precision ? 0 : $time - $$k * $v; 
      $s = $$k > 1 ? 's' : ''; 
      $$k = $$k ? $$k.' '.$k.$s.' ' : ''; 
      @$result .= $$k; 
    } 
  return $result ? $result.'ago' : '1 sec to go'; 
} 

function GET_value($key,$default_value='')
{
   $value=isset($_GET[$key])? $_GET[$key] : $default_value;
   if (is_string($value))$value=trim($value);
   return $value;

}

// Get a POST vairable, if the variable is not present, take the default value
function POST_value($key,$default_value='')
{
   $value=isset($_POST[$key])? $_POST[$key] : $default_value;
   if (is_string($value))$value=trim($value);
   return $value;
}

//Get a COOKIE vairable, if the variable is not present, take the default value
function COOKIE_value($key,$default_value='')
{
   $value=isset($_COOKIE[$key])? $_COOKIE[$key] : $default_value;
   if (is_string($value))$value=trim($value);
   return $value;

}

//Get a SESSION vairable, if the variable is not present, take the default value
function SESSION_value($key,$default_value='')
{
   $value=isset($_SESSION[$key])? $_SESSION[$key] : $default_value;
   if (is_string($value))$value=trim($value);
   return $value;

}

// Prepare variable for mysql queries
function quote_smart($value)
{
    // trim strings
    if (is_string($value))$value=trim($value);

    // Stripslashes
    if (get_magic_quotes_gpc()) {
        $value = stripslashes($value);
    }
    if (empty($value)) return "''";
    if (!is_numeric($value)) {
        $value = "'" . mysql_real_escape_string($value) . "'";
    }
    return $value;
}
function qs($value) //alias of quote_smarrt
{
   return quote_smart($value);   
}
/// 
function  clean_text($word){
    $word=trim($word);
    $word=strip_tags($word);
    if (get_magic_quotes_gpc()) {
        $word = stripslashes($word);
    }
    $word=mysql_real_escape_string($word);
    return $word;
}

//Update from an array
function mysql_update($table,$updates,$where){
    global $dbdefault;
    $update = implode(', ', $updates);
    $query = "UPDATE $table SET $update WHERE $where";
    //echo $query;
    $res = @mysql_query($query,$dbdefault);
    if ($res){
        return array('success'=>TRUE);
    }else{
        return array('success'=>FALSE,'error'=>  mysql_error());
    }
}

// Make a random string which has length of $length
function str_makerand ($length, $useupper=false,$usenumbers=false, $usespecial=false)
{
    $charset = "abcdefghijklmnopqrstuvwxyz";
    if ($useupper)   $charset .= "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    if ($usenumbers) $charset .= "0123456789";
    if ($usespecial) $charset .= "~@#$%^*()_+-={}|][";   // Note: using all special characters this reads: "~!@#$%^&*()_+`-={}|\\]?[\":;'><,./";
    $key='';
    for ($i=0; $i<$length; $i++) $key .= $charset[(mt_rand(0,(strlen($charset)-1)))];
    return $key;
}


function format_time($time_stamp)
{
   global $_text;
   $now=time();
   $past_seconds=$now-$time_stamp;
   $past_minutes=floor($past_seconds/60);
   $past_hours=floor($past_seconds/3600);
   $past_days=floor($past_seconds/(24*3600));

   if ($past_days>1)
      $time="$past_days $_text[days]"."<span class='listing_key'> ".$_text['ago']."</span>";
   else if ($past_days>0)
      $time="$past_days $_text[day] $_text[ago]";
   else if ($past_hours>1)
      $time="$past_hours $_text[hours] $_text[ago]";
   else if ($past_hours>0)
      $time="$past_hours $_text[hour] $_text[ago]";
   else if ($past_minutes>1)
      $time="$past_minutes $_text[minutes] $_text[ago]";
   else //if ($past_minutes>0)
      $time="$past_minutes $_text[minute] $_text[ago]";
   return $time;
}

function format_time2($time_stamp)
{
   global $_text;
   $now=time();
   $tmp = $now - $time_stamp;
   if ($tmp > 0)
      $past_seconds=$tmp;
   else
   {
      $past_seconds= $tmp*(-1);
   }
    
   $past_minutes=floor($past_seconds/60);
   $past_hours=floor($past_seconds/3600);
   $past_days=floor($past_seconds/(24*3600));

   if ($past_days>1)
      $time="$past_days $_text[days]"."<span class='listing_key'></span>";
   else if ($past_days>0)
      $time="$past_days $_text[day]";
   else if ($past_hours>1)
      $time="$past_hours $_text[hours]";
   else if ($past_hours>0)
      $time="$past_hours $_text[hour]";
   else if ($past_minutes>1)
      $time="$past_minutes $_text[minutes]";
   else //if ($past_minutes>0)
      $time="$past_minutes $_text[minute]";
   if ($tmp > 0)
      $time .= "<font color='red'> ".$_text['ago']."</font>";
   return $time;
}


//
function get_micro_time()
{
   list($usec, $sec) = explode(" ",microtime());
   return ((float)$usec + (float)$sec);
}
//

function format_duration($dur)
{

   $hh=floor($dur/3600);
   $mm=floor($dur/60) - $hh*60;
   $ss=$dur - $hh*3600 - $mm*60;
   if ($hh>0) return "${hh}h${mm}m";
   else if ($mm>0) return "${mm}m";
   else return "${ss}m";
}


// Similar to http_build_query of PHP 5 but simpler
function http_simple_query($array)
{
   $query='';
   foreach ($array as $key => $value)
   {
      if (is_array($value))
      {
         foreach ($value as $subkey => $subvalue)
         {
            $query.=$key."[$subkey]=".urlencode($subvalue).'&';
         }
      }
      else
         $query.=$key.'='.urlencode($value).'&';
   }
   return $query;
}


/*
*/
function trigger_error_page($message)
{
   require_once(WEBSITE_ROOT.'/common/class_Template.php');
   $pageinfo=new Pageinfo();
   $pageinfo->current_page = 'error';
   $pageinfo->page_title.=' - Error! ';
   $content='<div style="padding:50px;"><div class="error_message">'.$message.'</div></div>';

   $main_tpl = new Template(WEBSITE_ROOT.'/themes/main.html');
   $pageinfo->generate_pageinfo();
   $main_tpl->set('pageinfo', $pageinfo->data);
   $main_tpl->set('content', $content);
   echo $main_tpl->fetch();
   die();
}


//Check and create a directory if neccessary
function check_and_create_dir($dir)
{
   if (file_exists($dir))
   {
      if (is_dir($dir))
         return true;
      else
         return false; //file is not a directory!";
   }
   else  // try to create it
   {
      if (mkdir($dir, true))
      {
         chmod($dir,0777);
         return true;
      }
      else
         return false; // Cannot create
   }
}

// Remove <!--comment like this-->
function remove_html_comments($str){
   return preg_replace('/<!--(.|\s)*?-->/', '', $str); 
}


// High lighe
function hightlight($str, $keywords,$style = 'highlight')
{
    $keywords = preg_replace('/\s\s+/', ' ', strip_tags(trim($keywords))); // filter
    $keywords=explode(' ', $keywords);
    foreach($keywords as $k){
       $k=trim($k);
       $pat="/\b(${k})\b/i";
       $str = preg_replace("$pat", '<span class="'.$style.'">$1</span>', $str);
    }
    return $str;
}

//For script times
function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

function is_mobile1()
{
    $useragent=$_SERVER['HTTP_USER_AGENT'];  
    if(preg_match('/android|ipad|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i',substr($useragent,0,4)))  
    { return true;}
    else {return false;}
}


function is_mobile(){
    $op = isset($_SERVER['HTTP_X_OPERAMINI_PHONE'])?1:'';
    $ua = strtolower($_SERVER['HTTP_USER_AGENT']);
    $ac = strtolower($_SERVER['HTTP_ACCEPT']);
    if (strpos($ac, 'application/vnd.wap.xhtml+xml') !== false
        || $op != ''
        || strpos($ua, 'sony') !== false 
        || strpos($ua, 'symbian') !== false 
        || strpos($ua, 'nokia') !== false 
        || strpos($ua, 'samsung') !== false 
        || strpos($ua, 'mobile') !== false
        || strpos($ua, 'windows ce') !== false
        || strpos($ua, 'epoc') !== false
        || strpos($ua, 'opera mini') !== false
        || strpos($ua, 'nitro') !== false
        || strpos($ua, 'j2me') !== false
        || strpos($ua, 'midp-') !== false
        || strpos($ua, 'cldc-') !== false
        || strpos($ua, 'netfront') !== false
        || strpos($ua, 'mot') !== false
        || strpos($ua, 'up.browser') !== false
        || strpos($ua, 'up.link') !== false
        || strpos($ua, 'audiovox') !== false
        || strpos($ua, 'blackberry') !== false
        || strpos($ua, 'ericsson,') !== false
        || strpos($ua, 'panasonic') !== false
        || strpos($ua, 'philips') !== false
        || strpos($ua, 'sanyo') !== false
        || strpos($ua, 'sharp') !== false
        || strpos($ua, 'sie-') !== false
        || strpos($ua, 'portalmmm') !== false
        || strpos($ua, 'blazer') !== false
        || strpos($ua, 'avantgo') !== false
        || strpos($ua, 'danger') !== false
        || strpos($ua, 'palm') !== false
        || strpos($ua, 'series60') !== false
        || strpos($ua, 'palmsource') !== false
        || strpos($ua, 'pocketpc') !== false
        || strpos($ua, 'smartphone') !== false
        || strpos($ua, 'rover') !== false
        || strpos($ua, 'ipaq') !== false
        || strpos($ua, 'au-mic,') !== false
        || strpos($ua, 'alcatel') !== false
        || strpos($ua, 'ericy') !== false
        || strpos($ua, 'up.link') !== false
        || strpos($ua, 'vodafone/') !== false
        || strpos($ua, 'wap1.') !== false
        || strpos($ua, 'wap2.') !== false)
        {return true;}
        else{ return false;}
}        

function is_bot(){
    $ua = strtolower($_SERVER['HTTP_USER_AGENT']);
    $ac = strtolower($_SERVER['HTTP_ACCEPT']);
    $ip = $_SERVER['REMOTE_ADDR'];
       if ($ip == '66.249.65.39' 
        || strpos($ua, 'googlebot') !== false 
        || strpos($ua, 'mediapartners') !== false 
        || strpos($ua, 'yahooysmcm') !== false 
        || strpos($ua, 'baiduspider') !== false
        || strpos($ua, 'msnbot') !== false
        || strpos($ua, 'slurp') !== false
        || strpos($ua, 'ask') !== false
        || strpos($ua, 'teoma') !== false
        || strpos($ua, 'spider') !== false 
        || strpos($ua, 'heritrix') !== false 
        || strpos($ua, 'attentio') !== false 
        || strpos($ua, 'twiceler') !== false 
        || strpos($ua, 'irlbot') !== false 
        || strpos($ua, 'fast crawler') !== false                        
        || strpos($ua, 'fastmobilecrawl') !== false 
        || strpos($ua, 'jumpbot') !== false
        || strpos($ua, 'googlebot-mobile') !== false
        || strpos($ua, 'yahooseeker') !== false
        || strpos($ua, 'motionbot') !== false
        || strpos($ua, 'mediobot') !== false
        || strpos($ua, 'chtml generic') !== false
        || strpos($ua, 'nokia6230i/. fast crawler') !== false){
            return true;
        } else {
            return false;
        }
            
    
}

function VN_unaccent($text)
{
  static $search, $replace;
  $trans=array(               'á'=>'a','à'=>'a','ả'=>'a','ã'=>'a','ạ'=>'a', 
                    'ă'=>'a', 'ắ'=>'a','ằ'=>'a','ẳ'=>'a','ẵ'=>'a','ặ'=>'a',         
                    'â'=>'a', 'ấ'=>'a','ầ'=>'a','ẩ'=>'a','ẫ'=>'a','ậ'=>'a',         
                              'Á'=>'A','À'=>'A','Ả'=>'A','Ã'=>'A','Ạ'=>'A', 
                    'Ă'=>'A', 'Ắ'=>'A','Ằ'=>'A','Ẳ'=>'A','Ẵ'=>'A','Ặ'=>'A',         
                    'Â'=>'A', 'Ấ'=>'A','Ầ'=>'A','Ẩ'=>'A','Ẫ'=>'A','Ậ'=>'A',
                              'đ'=>'d','Đ'=>'D','Ð'=>'D',
                              'é'=>'e','è'=>'e','ẻ'=>'e','ẽ'=>'e','ẹ'=>'e',
                    'ê'=>'e', 'ế'=>'e','ề'=>'e','ể'=>'e','ễ'=>'e','ệ'=>'e',
                              'É'=>'E','È'=>'E','Ẻ'=>'E','Ẽ'=>'E','Ẹ'=>'E', 
                    'Ê'=>'E', 'Ế'=>'E','Ề'=>'E','Ể'=>'E','Ễ'=>'E','Ệ'=>'E',
                              'í'=>'i','ì'=>'i','ỉ'=>'i','ĩ'=>'i','ị'=>'i', 
                              'Í'=>'I','Ì'=>'I','Ỉ'=>'I','Ĩ'=>'I','Ị'=>'I', 
                              'ó'=>'o','ò'=>'o','ỏ'=>'o','õ'=>'o','ọ'=>'o', 
                    'ô'=>'o', 'ố'=>'o','ồ'=>'o','ổ'=>'o','ỗ'=>'o','ộ'=>'o',         
                    'ơ'=>'o', 'ớ'=>'o','ờ'=>'o','ở'=>'o','ỡ'=>'o','ợ'=>'o',         
                              'Ó'=>'O','Ò'=>'O','Ỏ'=>'O','Õ'=>'O','Ọ'=>'O', 
                    'Ô'=>'O', 'Ố'=>'O','Ồ'=>'O','Ổ'=>'O','Ỗ'=>'O','Ộ'=>'O', 
                    'Ơ'=>'O', 'Ớ'=>'O','Ờ'=>'O','Ở'=>'O','Ỡ'=>'O','Ợ'=>'O',         
                              'ú'=>'u','ù'=>'u','ủ'=>'u','ũ'=>'u','ụ'=>'u', 
                    'ư'=>'u', 'ứ'=>'u','ừ'=>'u','ử'=>'u','ữ'=>'u','ự'=>'u', 
                              'Ú'=>'U','Ù'=>'U','Ủ'=>'U','Ũ'=>'U','Ụ'=>'U', 
                    'Ư'=>'U', 'Ứ'=>'U','Ừ'=>'U','Ử'=>'U','Ữ'=>'U','Ự'=>'U', 
                              'ý'=>'y','ỳ'=>'y','ỷ'=>'y','ỹ'=>'y','ỵ'=>'y', 
                              'Ý'=>'Y','Ỳ'=>'Y','Ỷ'=>'Y','Ỹ'=>'Y','Ỵ'=>'Y' );
  if (!$search)
  {
    $search = $replace = array(); // Get the HTML entities table into an array
    //$trans = get_html_translation_table(HTML_ENTITIES); // Go through the entity mappings one-by-one
    //print_r($trans);
    foreach ($trans as $literal => $entity)
    { // Make sure we don�t process any other characters // such as fractions, quotes etc:
      if (ord($literal) >= 192)
      { // Get the accented form of the letter
        $search[] = $literal; // Get e.g. �E� from the string �ɒ $replace[] = $entity1;
        $replace[]= $entity;
      }
    }
  }
  return str_replace($search, $replace, $text);
}


//This function read a CSV file and return the whole content to an array (so the file must not be too big)
//if header=true, the the array is an associate array
function read_CSV($file,$header=true){
    $row = 1;
    $csv=array();
    if (($handle = fopen($file, "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            if($header){
                if ($row==1){
                    $hs = $data;
                }else{
                    $r=array();$num=count($data);
                    for ($c=0; $c < $num; $c++) {
                        $r[$hs[$c]]=$data[$c];
                    }
                    $csv[]=$r;
                }
            }else{
                $csv[]=$data;
            }
            $row++;
        }
        return $csv;
        fclose($handle);
   }else{
       return false;
   }         

}


function debug_data ( $data ) {
    echo '<pre>';
    if ( is_array( $data ) ) {
        print_r ( $data );
    } else {
        var_dump ( $data );
    }
    echo '</pre>';
}